package com.sweetguy.component;

import com.sweetguy.exception.ServiceException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import com.sweetguy.result.Result;
import com.sweetguy.result.ResultCode;



@Slf4j
@RestControllerAdvice(basePackages = {"com.sweetguy"})
public class ExceptionAdvice {

    @ExceptionHandler(ServiceException.class)
    public Object serviceException(ServiceException e) {
        log.error("业务异常:" + e.getMessage());
        return new Result<>(ResultCode.FAILED, e.getMessage());
    }

    @ExceptionHandler({MethodArgumentNotValidException.class, BindException.class})
    public Object methodArgumentNotValidException(Exception e) {

        //
        BindingResult bindingResult;
        if (e instanceof MethodArgumentNotValidException) {
            bindingResult = ((MethodArgumentNotValidException) e).getBindingResult();
        } else {
            bindingResult = ((BindException) e).getBindingResult();
        }

        //
        FieldError firstFieldError = bindingResult.getFieldErrors().get(0);

        //
        String message = String.format("%s实例的%s属性校验失败: %s", firstFieldError.getObjectName(), firstFieldError.getField(), firstFieldError.getDefaultMessage());

        //
        log.error(message);

        //
        return new Result<>(ResultCode.FAILED, message);
    }

    @ExceptionHandler(Exception.class)
    public Object exception(Exception e) {
        log.error("其他异常:" + e.getMessage());
        return new Result<>(ResultCode.FAILED, e.getMessage());
    }
}
